﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.DirectoryServices;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Tools;
using InfraTools.Forms;

namespace InfraTools.Class
{

    //Container barcode

    public class BarCode
    {

        public BarCode(string ItemType)
        {

            itemtype = ItemType;
        }


        public BarCode(string ItemType,string hostname)
        {
            Hostname = hostname;
            itemtype = ItemType;
        }

        public string itemtype { get; set; }
        public string Hostname { get; set; }
        public string Serial { get; set; }
        public string PN { get; set; }
        public string uuid { get; set; }
        public string type { get; set; }
        public string MAC { get; set; }
        public GlpiComputer PC { get; set; }

        
        public string Mac2Valid(string macAddress)
        {
            if (macAddress.StartsWith("23S") && macAddress.Length == 15 && System.Text.RegularExpressions.Regex.IsMatch(macAddress.Substring(3, 12), @"\A\b[0-9a-fA-F]+\b\Z"))
            {
                return macAddress.Substring(3, 2) + ':' + macAddress.Substring(5, 2) + ':' + macAddress.Substring(7, 2) +
                             ':' + macAddress.Substring(9, 2) + ':' + macAddress.Substring(11, 2) + ':' + macAddress.Substring(13, 2);

            }

            else if (macAddress.Contains(":") && macAddress.Length == 17)
            {

                return macAddress;
            }

            string result = "";
            Regex rx = new Regex("([0-9a-fA-F][0-9a-fA-F]-){5}([0-9a-fA-F][0-9a-fA-F])", RegexOptions.IgnoreCase);
            Match m = rx.Match(macAddress);
            result = m.Groups[0].Value;

            if (result.Length == 17 && result.Contains(":"))
            {
                return result;
            }
            else
            {
                rx = new Regex("([0-9a-fA-F][0-9a-fA-F]){5}([0-9a-fA-F][0-9a-fA-F])", RegexOptions.IgnoreCase);
                Match m2 = rx.Match(macAddress);
                result = m2.Groups[0].Value;
                if (result.Length == 12)
                {
                    string resultmod = result.Substring(0, 2) + ':' + result.Substring(2, 2) + ':' + result.Substring(4, 2) + ':' + result.Substring(6, 2) + ':' + result.Substring(8, 2) + ':' + result.Substring(10, 2);
                    return resultmod;
                }
                return "bad";
            }
        }

        public void get1s(string PnSn)
        {
            if (PnSn.StartsWith("1S") && PnSn.Length == 16 && itemtype == "Computer")
            {
                PN = PnSn.Substring(2, 7);
                Serial = PnSn.Substring(9, 7);

            }
            else if (PnSn.StartsWith("1S") && PnSn.Length == 16 && itemtype == "Monitor")
            {
                PN = PnSn.Substring(2, 7);
                Serial = PnSn.Substring(9, 2) + "-" + PnSn.Substring(11, 5);
            }


        }

        public string UUID2Valid(string UUID)
        {
            if (UUID.StartsWith("30S") && UUID.Length == 35 && System.Text.RegularExpressions.Regex.IsMatch(UUID.Substring(3, 32), @"\A\b[0-9a-fA-F]+\b\Z"))
            {
                return UUID.Substring(3, 8) + '-' + UUID.Substring(11, 4) + '-' + UUID.Substring(15, 4) + '-' + UUID.Substring(19, 4) + '-' + UUID.Substring(23, 12);

            }

            else if (System.Text.RegularExpressions.Regex.IsMatch(UUID, @"^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$"))
            {

                return UUID;
            }
            else if (UUID.Length == 32 && System.Text.RegularExpressions.Regex.IsMatch(UUID, @"\A\b[0-9a-fA-F]+\b\Z"))
            {
                return UUID.Substring(0, 8) + '-' + UUID.Substring(9, 4) + '-' + UUID.Substring(13, 4) + '-' + UUID.Substring(16, 4) + '-' + UUID.Substring(20, 12);
            }


            return "bad";

        }

        public void getbarcode(string barcode)
        {
            barcode = barcode.ToUpper();
            type = "Notvalid";

            if ((barcode.StartsWith("23S") && barcode.Length == 15 && System.Text.RegularExpressions.Regex.IsMatch(barcode.Substring(3, 12), @"\A\b[0-9a-fA-F]+\b\Z")) || (barcode.Contains(":") && barcode.Length == 17) || (barcode.Length == 12 && System.Text.RegularExpressions.Regex.IsMatch(barcode.Substring(0, 12), @"\A\b[0-9a-fA-F]+\b\Z")))
            {
                type = "mac";

                MAC = Mac2Valid(barcode);

            }


            else if (barcode.StartsWith("1S"))
            {
                type = "modelserial";
                get1s(barcode);
            }


            else if ((barcode.StartsWith("30S") && barcode.Length == 35 && System.Text.RegularExpressions.Regex.IsMatch(barcode.Substring(3, 32), @"\A\b[0-9a-fA-F]+\b\Z")) || (barcode.Length == 32 && System.Text.RegularExpressions.Regex.IsMatch(barcode, @"\A\b[0-9a-fA-F]+\b\Z")))
            {
                type = "uuid";
                uuid = UUID2Valid(barcode);
            }

            else if ((barcode.StartsWith("30S") && barcode.Length == 35 && System.Text.RegularExpressions.Regex.IsMatch(barcode.Substring(3, 32), @"\A\b[0-9a-fA-F]+\b\Z")) || (barcode.Length == 32 && System.Text.RegularExpressions.Regex.IsMatch(barcode, @"\A\b[0-9a-fA-F]+\b\Z")))
            {
                type = "uuid";
                uuid = UUID2Valid(barcode);
            }

            else if (System.Text.RegularExpressions.Regex.IsMatch(barcode, @"^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$"))
            {

                type = "uuid";
                uuid = UUID2Valid(barcode);
            }



            else if (System.Text.RegularExpressions.Regex.IsMatch(barcode, @"[A-Z]{4,10}\d{4}"))
            {
                type = "hostname";
                Hostname = barcode;
            }

            

        }

        public void GetCNewComputer(String Barcode)
        {
            getbarcode(Barcode);
            frmNewComputer NewCompuFrm = new frmNewComputer();
            NewCompuFrm.BC = this;
            NewCompuFrm.Hostname = this.Hostname;
            NewCompuFrm.Show();
            PC = NewCompuFrm.temppc.GetGlpiComputer();
            
            

            
        }
        
    }


    public class Infratoolbox
    {

        public List<ArrayList> FreeComputerNames { get; set; }
        public bool getFCNdone { get; set; }
        public bool getFCNbusy { get; set; }
        public string  getFCNMSG { get; set; }

        private string[] pctypes ;
        public List<CmbObject> Choises { get; set; }
        public List<CmbObject> PCtypes { get; set; }
        public List<CmbObject> Objecttypes { get; set; }
        

        public Glpi glpicon;
        public Sccm sccmcon; 
        public string SccmCollection;
        
        
        public Infratoolbox()
        {
            getFCNbusy = false;
            getFCNdone = false;

            

            FreeComputerNames = new List<ArrayList>();

            //Choises
            Choises = new List<CmbObject>();
            Choises.Add(CreateAction(1, "Add To Sccm"));
            Choises.Add(CreateAction(2, "Add to Inventory (Glpi)"));
            Choises.Add(CreateAction(3, "Recycle - set Stock"));
            Choises.Add(CreateAction(4, "Remove - set Stock Out of lease"));
            Choises.Add(CreateAction(5, "Print Label"));
            //Objecttypes
            Objecttypes = new List<CmbObject>();
            Objecttypes.Add(CreateAction(1, "Computer"));
            Objecttypes.Add(CreateAction(2, "Monitor"));


            pctypes = Properties.Settings.Default.ComputerTypes.Split(',');
            PCtypes = new List<CmbObject>();
            for (int n = 0; n < Properties.Settings.Default.ComputerTypes.Split(',').Count(); n++)
            {
                PCtypes.Add(CreateAction(n, pctypes[n]));
                FreeComputerNames.Add(new ArrayList());
            }



        }

        //public List<Computers> DoAcction(int choice ,List<Computers> computerlist)
        public void DoAcction(int choice)
        {
            switch (choice)
            {
                case 1:
                    MessageBox.Show("choice1");
                    break;
                case 2:
                    MessageBox.Show("choice2");
                    break;
                case 3:
                    MessageBox.Show("choice3");
                    break;
                case 4:
                    MessageBox.Show("choice4");
                    break;

                default:
                    //do default
                    break;
            }

        }

        private CmbObject CreateAction(int id, string name)
        {
            CmbObject cmb = new CmbObject();
            cmb.Id = id;
            cmb.Name = name;
            return cmb;


        }

        private void populateFPCN()
        {
            for (int i = 0; i < pctypes.Count(); i++)
            {


                int index = i;
                ArrayList adpc = new ArrayList();
                ArrayList freepc = new ArrayList();
                ArrayList pclist = new ArrayList();
                ArrayList Glpipc = glpicon.GetGlpiComputers(pctypes[i]);
                ArrayList Sccmpclist = sccmcon.SccmComputers(SccmCollection);

                try
                {
                    DirectoryEntry Ldap = new DirectoryEntry(Properties.Settings.Default.ADSPath);
                    Ldap.Username = sccmcon.SccmUserName;
                    Ldap.Password = sccmcon.SccmPassword;
                    DirectorySearcher searcher = new DirectorySearcher(Ldap);
                    searcher.Filter = "(&(objectCategory=computer)(name=" + pctypes[i] + "*))";


                    foreach (SearchResult result in searcher.FindAll())
                    {
                        // On récupère l'entrée trouvée lors de la recherche
                        DirectoryEntry DirEntry = result.GetDirectoryEntry();

                        //On peut maintenant ajouter les informations désirées dans l'ArrayList

                        adpc.Add(DirEntry.Properties["cn"].Value);

                    }

                    for (int x = 0; x < int.Parse(Properties.Settings.Default.MaxNumPC); x++)
                    {

                        pclist.Add(pctypes[i] + x.ToString().PadLeft(4, '0'));

                    }



                    adpc.Sort();
                    foreach (var item in pclist)
                    {

                        if (!adpc.Contains(item) && !Sccmpclist.Contains(item) && !Glpipc.Contains(item))
                        {

                            FreeComputerNames[i].Add(item);
                        }

                    }


                    getFCNdone = true;


                }



                catch (Exception Ex)
                {
                    System.Windows.Forms.MessageBox.Show(Ex.Message, "Error adding Computer", MessageBoxButtons.OK);
                    getFCNdone = false;

                }
            }
        }

        public string getfreepcname(int type)
        {
            for (int i = 0; i < FreeComputerNames[type].ToArray().Length; i++)
			{
                foreach (string s in FreeComputerNames[type])
                {
                    if (!string.IsNullOrEmpty(s))
                    {
                        FreeComputerNames[type].IndexOf(s);
                        string temp = s;
                        FreeComputerNames[type].RemoveAt(FreeComputerNames[type].IndexOf(s));
                        return temp;

                    }
                     
                }
                 
			}
            return "No Free PC";  
      
        }

        public void UpdateFPCL(Glpi Glpicon, Sccm Sccmcon, string sccmcollection)
        {
           glpicon = Glpicon ;
           sccmcon = Sccmcon ; 
           SccmCollection = sccmcollection;
           BackgroundWorker bw = new BackgroundWorker();

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoUpdateFPCN);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_UpdateFPCNProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunUpdateFPCNCompleted);

            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }

        }

        private void bw_DoUpdateFPCN(object sender, DoWorkEventArgs e)
        {

            BackgroundWorker worker = sender as BackgroundWorker;



                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    
                    
                }

                else
                {
                    getFCNbusy = true;
                    populateFPCN();
                   
                }
            
        }

        private void bw_RunUpdateFPCNCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            if ((e.Cancelled == true))
            {
                this.getFCNMSG = "Cancelled";
                this.getFCNbusy = false;
                this.getFCNdone = false ;
            }


            else if (!(e.Error == null))
            {
                this.getFCNMSG = ("Error: " + e.Error.Message);
                this.getFCNbusy = false;
                this.getFCNdone = false ;
            }



            else
            {
                this.getFCNMSG = "Done!";
                this.getFCNbusy = false;
                this.getFCNdone = true ;
            }

        }

        private void bw_UpdateFPCNProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.getFCNbusy = true;
            this.getFCNMSG = "Busy";

        }


       
    }



    }



